<template>
  <div class="drawer-entry">
    <el-drawer
      append-to-body
      :title="title"
      :visible.sync="visible"
      custom-class="trigger-drawer"
      ref="drawer"
      :size="drawerSize"
    >
      <div class="drawer-content" v-if="visible">
        <div class="drawer-form">
          <start-app-drawer
            v-if="app.type == 0"
            ref="startNodeDrawerDom"
            :nodeConfig.sync="app"
            :moduleList="moduleListFrom"
          />
          <trigger-drawer
            ref="triggerDrawerDom"
            v-if="app.type == 1"
            :nodeConfig.sync="app"
            :moduleList="moduleListTo"
            :parent="parent"
          />
          <condition-drawer
            v-if="app.type == 2"
            :nodeConfig.sync="app"
            :moduleList="moduleListTo"
            :parent="parent"
          />
          <action-app-drawer
            v-if="app.type == 3"
            :nodeConfig.sync="app"
            :moduleList="moduleListTo"
            :parent="parent"
            @immediatelyUpdate="immediatelyUpdateNodeConfig"
          />
          <message-drawer
            v-if="app.type == 4"
            :nodeConfig.sync="app"
            :parent="parent"
            ref="messageDrawRef"
          />
          <code-drawer
            v-if="app.type == 6"
            :nodeConfig.sync="app"
            :parent="parent"
            ref="codeDrawerRef"
          />
        </div>
        <div class="drawer-footer">
          <el-button @click="cancelForm">{{ $t('common.base.cancel') }}</el-button>
          <el-button type="primary" @click="submit">{{ $t('common.base.save') }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import startAppDrawer from './startApp.vue';
import triggerDrawer from './trigger.vue';
import actionAppDrawer from './actionApp.vue';
import conditionDrawer from './condition.vue';
import messageDrawer from './message.vue';
import codeDrawer from './code.vue';

import _ from 'lodash';
import { findComponentsDownward } from '@src/util/assist'
import { isNotTrue, isFalse, cloneDeep } from '@src/util/type'
import { t } from '@src/locales'

const titleList = {
  0: t('common.connector.trigger.startApp'),
  1: t('trigger.text7'),
  2: t('common.connector.trigger.conditionSetting'),
  3: t('common.connector.trigger.executeApp'),
  4: t('common.connector.trigger.setNotificationRule'),
  6: '设置执行代码',
}
export default {
  name: 'node-drawer',
  props: {
    nodeConfig: {
      type: Object,
      default: () => ({}),
    },
    moduleListFrom: {
      type: Array,
      default: () => [],
    },
    moduleListTo: {
      type: Array,
      default: () => [],
    },
    parent:{
      type: Object,
      default: () => ({}),
    }
  },
  computed:{
    title(){
      return titleList[this.nodeConfig.type]
    },
    drawerSize() {
      return this.app?.type == 0 || this.app?.type == 1 ? '420px' : '640px'
    },
  },
  watch: {
    nodeConfig: {
      handler(newVal) {
        this.app = _.cloneDeep(newVal);
      },
      deep: true,
      immediate: true
    },
  },
  data() {
    return {
      app: null,
      visible:false
    };
  },
  methods: {
    open(){
      this.app = _.cloneDeep(this.nodeConfig)
      this.visible = true
    },
    cancelForm(){
      this.visible = false
    },
    async submit() {
      
      // 执行应用，校验某些字段数据的正确定
      const isExecuteApplication = this.app.type == 3
      
      if (isExecuteApplication) {
        
        const formItemComponents = findComponentsDownward(this, 'form-item')
        const allValidateMicroTasks = formItemComponents.map(formItemComponent => formItemComponent.validate())
        const results = await Promise.all(allValidateMicroTasks)
        
        const isValidateFail = (
          results
            .filter(result => isNotTrue(result))
            .filter(result => isFalse(result) || Boolean(result))
        )
        
        if (isValidateFail.length) {
          console.warn('validate fail')
          return
        }
        let flag = false
        const { bizType, executeAction } = this.app.data
        const insertFieldOptions = executeAction?.insertFieldOptions || []
        insertFieldOptions.forEach(option =>{
          if(bizType === 'WIKI' && option.field.formType === 'rich_text' && !option.value) {
            // 触发器富文本不能为空
            this.$message.warning(this.$t('common.wiki.contentValidate'))
            flag = true
          }
        })
        if(flag) return
      }
      if(this.app.type == 4) {
        // 消息的保存
        const params = await this.$refs.messageDrawRef.getMessageParams()
        params.isEditMessage = true
        this.app.data = params
        // console.log('app.data', this.app.data)
      }
      if (this.app.type == 6) {
        // 代码的保存
        const params = this.$refs.codeDrawerRef.getCodeParams()
        if (params?.code === '') {
          this.$message.warning('执行代码不能为空')
          return
        } else if (params?.title === '') {
          this.$message.warning('执行代码名称不能为空')
          return
        }
        this.app.data = params
      }
      // console.log('draw index app.data', this.app.data)
      let timerOptions = await this.$refs.startNodeDrawerDom?.getTimerOptions()
      if(timerOptions === false) return
      this.nodeConfig.data = timerOptions ? { ...this.app.data, timerOptions } : this.app.data

      // 不是条件的重新赋值下childNodes
      if(this.app.type !== 2) {
        this.nodeConfig.childNodes = this.app.childNodes
      }

      // 如果是条件的话，需要清空
      if(this.nodeConfig.data.convertType == 'fieldMapping' && this.app.type == 2){
        this.nodeConfig.data.convertCode = ''
      } else if (this.app.type == 2){
        this.nodeConfig.data.conditionList = [[]]
      }

      this.$emit('update:nodeConfig', this.nodeConfig)
      this.visible = false
    },
    immediatelyUpdateNodeConfig(v) {
      // 为了防止数据丢失
      this.nodeConfig.childNodes = cloneDeep(v.childNodes)
      
      // 修改加载后的初始化表单数据
      this.nodeConfig.data.executeAction = cloneDeep(v.data.executeAction)

    }
  },
  components: {
    [startAppDrawer.name]: startAppDrawer,
    [triggerDrawer.name]: triggerDrawer,
    [actionAppDrawer.name]: actionAppDrawer,
    [conditionDrawer.name]: conditionDrawer,
    [messageDrawer.name]: messageDrawer,
    [codeDrawer.name]: codeDrawer,
  },
};
</script>